package xyz.dfm.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import xyz.dfm.service.UserMapperRemote;

import java.util.List;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserMapperRemote userMapperRemote;

    /**
     * 认证逻辑
     * @param s 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //查询用户是否存在
        xyz.dfm.pojo.User user = userMapperRemote.selectUserByUsername(s);
        if (user == null){
            throw new UsernameNotFoundException("User Not Found");
        }
        //查询用户权限
        List<String> permission = userMapperRemote.selectUserPermission(user.getUserId());
        return new User(s, user.getUserPassword(),
                AuthorityUtils.createAuthorityList(permission.toArray(permission.toArray(new String[0]))));
    }
}
